# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict
import base64

import requests
import random
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)


APP_CONF = {
    # '9990001': {  # 测试
    #     'API_KEY': 'bfc994e0165143a6bbdaf52c2c141fee',
    #     'gateway': 'http://103.230.240.50:12345/hydra/api/charge/create/',
    #     'query_gateway': 'http://103.230.240.50:12345/hydra/api/charge/query/',
    # },
    '9990001': {
        'API_KEY': '6df03bc8d7d04348a61f8042b8d457d1',
        'gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/create/',
        'query_gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/query/',
    },
    '9990002': {
        'API_KEY': '7f64a8d4820f43378b23ab1001887c8c',
        'gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/create/',
        'query_gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/query/',
    },
    '9990003': {
        'API_KEY': '1172e897df4c4f5c89e3535cb80d8c55',
        'gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/create/',
        'query_gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/query/',
    },
    '9990004': {  # loki
        'API_KEY': '0eed9f4228404bada599a4f3ae9e2e8d',
        'gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/create/',
        'query_gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/query/',
    },
    '9990006': {  # RM
        'API_KEY': 'e65058eab17e4436ab5c3b58b890116c',
        'gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/create/',
        'query_gateway': 'http://hydra.xyz115.com:12345/hydra/api/charge/query/',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    _LOGGER.info("hydra sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("hydra sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('body', 'charge'),
        ('extra', 'charge'),
        ('pay_type', service),
        ('total_fee', pay_amount),
        ('user_ip', _get_device_ip(info)),
        ('user_id', pay.user_id),
        ('notify_url', '{}/pay/api/{}/hydra/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("hydra create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("hydra create rsp: %s", response.text)
    data = json.loads(response.text)['data']
    trade_id = data.get('trade_id')
    template_data = {}
    p_u = data['pay_url']
    if trade_id:
        order_db.fill_third_id(pay.id, trade_id)
    if service == 'qr_alipay':
        template_data['amount'] = pay_amount
        template_data['real_amount'] = data['real_amount']
        template_data['payee'] = p_u[p_u.find('bankAccount=') + 12:p_u.find('&money')]
        template_data['cardNo'] = p_u[p_u.find('cardNo=') + 7:p_u.find('&bankAccount')]
        template_data['bankName'] = p_u[p_u.find('bankName=') + 9:]
        template_data['remit'] = round(float(pay_amount - data['real_amount']), 2)
        t = get_template('qr_alipay2.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("hydra create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    elif service == 'link_alipay':
        pay_url = _get_pay_url(template_data, data, pay, service)
        return {'charge_info': pay_url}
    elif service == 'cloud_flash':
        template_data['real_amount'] = data['real_amount']
        template_data['cardNo'] = p_u[p_u.find('cardNo=') + 7:p_u.find('&bankAccount')]
        template_data['cloud_url'] = 'http://image.barchain.net/cloud_flash/qr/{}.png'.format(template_data['cardNo'])
        t = get_template('cloud_flash_hydra.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("hydra create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    elif service == 'scan_code':
        pay_url = _get_pay_url(template_data, data, pay, service)
        template_data['real_amount'] = data['real_amount']
        template_data['total_fee'] = data['total_fee']
        template_data['url'] = pay_url
        t = get_template('scan_code_first.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("hydra create_scan_code_first_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    else:
        return {'charge_info': data['pay_url'], 'order_amount': pay_amount, 'real_amount': data['real_amount']}


def _get_pay_url(template_data, data, pay, service):
    link_alipay_key = '8f75b8d5931g54478c23bc2111887d9d'
    domain_list = ['https://a.668at.com', 'https://a.weixinxi.net']
    template_data['real_amount'] = data['real_amount']
    template_data['alipay_id'] = data['alipay_id']
    template_data['sign'] = generate_sign(template_data, link_alipay_key)
    template_data['encryption_str'] = '{"real_amount":"' + str(template_data['real_amount']) + \
                                      '","alipay_id":"' + template_data['alipay_id'] + \
                                      '","sign":"' + template_data['sign'] + '"}'
    template_data['encryption_key'] = base64.b64encode(template_data['encryption_str'].encode('utf-8'))
    template_data['url'] = '{}/hydra/api/link/create/?key=' \
                           '{}'.format(domain_list[random.randint(0, (len(domain_list) - 1))],
                                       template_data['encryption_key'])

    t = get_template('link_alipay.html')
    if service == 'scan_code':
        t = get_template('scan_code_second.html')
    html = t.render(Context(template_data))
    cache_id = redis_cache.save_html((str(pay.id) + service), html)
    _LOGGER.info("hydra create_scan_code_second_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    pay_url = settings.PAY_CACHE_URL + cache_id
    return pay_url


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("hydra notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('hydra event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['pay_result'])
    trade_no = data['trade_no']
    total_fee = float(data['total_fee'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '2':
        _LOGGER.info('hydra check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('out_trade_no', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('hydra query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('hydra query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        mch_id = pay_order.mch_id
        trade_status = str(data['pay_result'])
        total_fee = float(data['total_fee'])
        trade_no = data['trade_no']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '2':
            _LOGGER.info('hydra query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
